/**
 * Created with JetBrains WebStorm.
 * User: Endre Balogh
 * Date: 5/31/13
 * Time: 1:30 PM
 * To change this template use File | Settings | File Templates.
 */

'use strict';

angular.module('ender.game.gambling-den', [ 'ender.game.boardgames' ])
    .controller('GamblersController', function ($scope, gamblerRepository) {
        $scope.gamblers = gamblerRepository.getGamblers();
    })
    .controller('PrepareBoardgameController', function ($scope, $routeParams, gamblerRepository, boardgameService) {
        $scope.gambler = gamblerRepository.getGamblerById($routeParams.gamblerId);

        var defaultRules;

        $scope.$watch('gambler.gameId', function (newValue) {
            if (newValue) {
                defaultRules = boardgameService.getCustomRules($scope.gambler.gameId);
                resetRules();
            }
        });
        function resetRules() {
            $scope.gameRules = angular.copy(defaultRules);
            for (var i = 0; i < $scope.gameRules.length; i++) {
                $scope.gameRules[i].value = $scope.gameRules[i].default;
            }
        }

        $scope.playWithCustomRules = false;
        $scope.$watch('playWithCustomRules', function (newValue, oldValue) {
            if (newValue !== oldValue) {
                if (newValue === false) {
                    resetRules();
                }
            }
        });

        $scope.practice = function () {
            boardgameService.startBoardGame($scope.gambler.gameId, $scope.gambler.name, $scope.gameRules, '#/gambling/gamblers/' + $routeParams.gamblerId);
        };
    })
    .factory('gamblerRepository', function factoryFunction( $resource, $q ){
        var resource = $resource('data/gamblers.json');
        var deferred = $q.defer();
        var gamblersById = {};
        var gamblers = resource.query(function(){

            for (var i=0; i<gamblers.length; i++){
                var gambler = gamblers[i];
                gamblersById[gambler.id] = gambler;
            }

            deferred.resolve();
        });


        return {
            getGamblers : function(){
                return gamblers;
            },
            getGamblerById : function(gamblerId){
                var gambler = {};

                deferred.promise.then(function(){
                    angular.extend(gambler, gamblersById[gamblerId]);
                })

                return gambler;
            }
        }
    });
